package com.lry.pda.bottom.mysql.innodb.compact;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.tuple.ImmutablePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class TableFrame {

    private String table;
    private String primaryKey;
    private List<FieldFrame> fieldFrameList;

    private Map<String,FieldFrame> fieldMap;

    public TableFrame(String table, String primaryKey, List<FieldFrame> fieldFrameList) {
        this.table = table;
        this.primaryKey = primaryKey;
        this.fieldFrameList = fieldFrameList;
        this.fieldMap = new HashMap<>();
        for (FieldFrame fieldFrame : fieldFrameList) {
            this.fieldMap.put(fieldFrame.getField(),fieldFrame);
        }
    }


    //变长字段列表，null列表，记录头40字节，tran_id,roll_pointer,col1,col2,col3....
    public byte[] getRowRecord(Map<String,Object> map){
        check(map);
        List<FieldFrame> stringFieldList = stringFieldList();
        ByteBuf buf = Unpooled.buffer();

        for (FieldFrame fieldFrame : stringFieldList) {
            Object obj = map.get(fieldFrame.getField());
            if(null!=obj){
                String val = (String) obj;

            }
        }

        byte[] bs = new byte[buf.readableBytes()];
        buf.readBytes(bs);
        return bs;
    }


    private List<FieldFrame> stringFieldList(){
        List<FieldFrame> stringFieldList = new ArrayList<>();
        for (FieldFrame fieldFrame : fieldFrameList) {
            if(fieldFrame.getFieldType().equals(String.class)){
                stringFieldList.add(0,fieldFrame);
            }
        }
        return stringFieldList;
    }

    private void check(Map<String,Object> map){
        for (FieldFrame fieldFrame : fieldFrameList) {
            if(fieldFrame.isNoNull()){
                if(null==map.get(fieldFrame.getField())){
                    throw new RuntimeException(String.format("字段%s不允许为空",fieldFrame.getField()));
                }
            }
            if(fieldFrame.getFieldType().equals(String.class)){
                Object obj = map.get(fieldFrame.getField());
                if(null!=obj){
                    String val = (String) obj;
                    if(val.length()>fieldFrame.getLength()){
                        throw new RuntimeException(String.format("字段%s长度超过限制",fieldFrame.getField()));
                    }
                }
            }
        }
    }
}
